$(function(){
    let $btn = $("#btn");
    let $username = $("#username");
    let $password = $("#password");
    $btn.on("click",function(){
        var options = {
            url:"http://127.0.0.1:8888/users/login",
            type:"POST",
            data:{
                username:$username.val(),
                password:$password.val()
            },
            dataType:"json"
        }
        $.ajax(options)
        .done(function(data){
            render(data);
        })
        function render(data){
            switch(data.code){
            case 0:
                errorTop(data.message);
                break;
            case 1:
                successTip(data.message);
                console.log(data);
                setTimeout(function(){
                    location.href="./index.html"
                },2000);
                setCookie("userid",data.user.id);
                setCookie("token",data.token,{
                    expires : 1 
                });
                break;
            }
        }
    })
    var $login_tip = $("#login_tip");
    function errorTop(msg){
        login_tip.style.display = "block";
        login_tip.classList.remove("alert-success");
        login_tip.classList.add("alert-danger");
        login_tip.innerHTML = msg;
        setTimeout(function(){
              login_tip.style.display = "none";
        } , 2000)
    };
    function successTip(msg){
        login_tip.classList.remove("alert-danger");
        login_tip.classList.add("alert-success");
        login_tip.style.display = "block";
        login_tip.innerHTML = msg;
        setTimeout(function(){
              login_tip.style.display = "none";
        } , 2000)
    };
})